package cn.wx.common.persistence.base;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.common.persistence.web.ResponseData;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;


/**
 *   @description : 控制器的基类
 *   ---------------------------------
 *   @author zj
 *   @since 2017-11-14
 */
public class BaseController {
	
	@Autowired
	private MessageSource messageSource;
	
	/**
	 * 自动将yyyy-MM-dd格式的参数转换成Date型参数
	 * 
	 * @param binder
	 * @throws RequestException
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder, HttpServletRequest request){
		/*SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat1.setLenient(true);*/

//		SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
//		dateFormat2.setLenient(true);

		//binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat1, true));
		//binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat2, true));

/*		if (binder.getObjectName().indexOf("QO") != -1) {
			BaseQO qo = (BaseQO) binder.getTarget();
			if (qo != null) {
				preHandle(request, qo);
			}
		} else if (binder.getObjectName().indexOf("Command") != -1) {
			BaseCommand command = (BaseCommand) binder.getTarget();
			if (command != null) {
				preHandle(request, command);
			}
		}*/
	}


	/**
     * @description : 接口请求成功返回
     * ---------------------------------
     * @author : zj
     * @since : Create in 2017-11-14
     */
	protected ResponseData success() {
		return success(null);
	}
	
	protected ResponseData success(Object object) {
		// 获取local
		Locale locale = LocaleContextHolder.getLocale();
		ResponseData rData = new ResponseData();
		rData.setCode(ResponseCode.SUCCESS);
		rData.setMsg(messageSource.getMessage(ResponseCode.SUCCESS, null, locale));
		rData.setData(object);
		return rData;
	}
	
	protected ResponseData success(Object object, String msg) {
		// 获取local
		Locale locale = LocaleContextHolder.getLocale();
		ResponseData rData = new ResponseData();
		rData.setCode(ResponseCode.SUCCESS);
		rData.setMsg(messageSource.getMessage(ResponseCode.SUCCESS, null, locale));
		rData.setData(msg);
		return rData;
	}
}
